<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>配置终端</title>
  <style>
    .bg-grey { background-color: #efefef; }
    .padding { padding: 2rem; }
    .hcenter { align-items: center; justify-content: center; }
  </style>
  <script id="template-info" type="text/html">
    <tbody>
      <tr><td>Auth user</td><td>{user}</td></tr>
      <tr><td>Chip id</td><td>{chipid}</td></tr>
      <tr><td>Heap free</td><td>{free}</td></tr>
      <tr><td>Memory in use</td><td>{use}</td></tr>
      <tr><td>Flash id</td><td>{fid}</td></tr>
      <tr><td>Flash size</td><td>{fsize}</td></tr>
      <tr><td>Flash mode</td><td>{fmode}</td></tr>
      <tr><td>Flash speed</td><td>{fspeed}</td></tr>
      <tr><td>AP MAC address</td><td>{amac}</td></tr>
      <tr><td>Station MAC address</td><td>{smac}</td></tr>
      <tr><td>NodeMCU version</td><td>{ver}</td></tr>
    </tbody>
  </script>
  <script id="template-sta-aplist" type="text/html">
		<div class="chip hand">
			<svg width="30px" height="20px" class="chip-icon">
				<path d="M15,20 L0.86,5.86 A20,20 0 0,1 29.14,5.86" fill="#d0d0d0" />
				<path d="M15,20 L{0},{1} A{2},{2} 0 0,1 {3},{1}" fill="#adadad" />
			</svg>
			<span class="chip-content">{4}</span>
		</div>
	</script>
  <script type="text/javascript">
    /* Download files one by one. To prevent server memory overflow. */
    function downloadByOrder(files, afterLoad) {
      let idx = 0;

      function addToEvent(ele, download) {
        if (ele.addEventListener) {
          ele.addEventListener("load", download, false);
        } else if (ele.attachEvent) {
          ele.attachEvent("onload", download);
        } else {
          ele.onload = download;
        }
      }
      function getOneFile() {
        if (idx >= files.length) return null;
        return files[idx++];
      }
      function guessType(file) {
        let pos = file.lastIndexOf(".");
        let ext = file.substring(pos+1);
        switch (ext) {
          case "js": return "script";
          case "css": return "link";
        }
        return null;
      }
      function downloadOneFile(file, onDone) {
        let type = guessType(file);
        if (!type) return;
        let element = document.createElement(type);
        if (type == "script") {
          element.src = file;
          element.type = "text/javascript";
        } else if (type == "link") {
          element.href = file;
          element.type = "text/css";
          element.rel = "stylesheet";
        }
        addToEvent(element, onDone);
        document.body.appendChild(element);
      }
      function download() {
        let file = getOneFile();
        if (!file) {
          if (afterLoad) afterLoad();
          return;
        }
        downloadOneFile(file, download);
      }

      addToEvent(window, download)
    }
    function toSpeed(speed) {
      return (speed/1000000) + 'MHz';
    }
    function toSize(size) {
      let k = Math.floor(size / 1024 / 1024);
      if (k > 0) return (size / 1024 / 1024).toFixed(1) + 'MB';
      k = Math.floor(size / 1024);
      if (k > 0) return (size / 1024).toFixed(1) + 'KB';
      return size + 'B';
    }

    downloadByOrder(["lib/spectre.min.css","lib/zepto.min.js","lib/sh.js"], function() {
      let tip_timer_id = null;
      function showTip(text, type, time) {
        window.clearTimeout(tip_timer_id);

        $('#tip_box_modal .toast').removeClass()
          .addClass('toast toast-' + type)
        $('#tip_box_modal label').text(text);
				$('#tip_box_modal').addClass('active');
        $("#tip_box_modal button").click(function() {
				  $('#tip_box_modal').removeClass('active');
          window.clearTimeout(tip_timer_id);
        });
        tip_timer_id = window.setTimeout(function() {
				  $('#tip_box_modal').removeClass('active');
        }, time);
      }

      function tabAClick(index) {
        $('.tab_nav>ul>li').eq(index).addClass('active')
          .siblings('li').removeClass('active');
        $('.title_info>section').eq(index).show()
          .siblings('section').hide()
        $('.box_content>div').eq(0).show()
          .siblings('div').hide();
        
        reqTab(index);
      }

      function switchUIEditInfo(index, edit) {
        $('.box_content>div').eq(index+1).show()
          .siblings('div').hide();
        if (index == 1) {
          if (edit) {
            $('#sta_content>form').removeClass('disabled');
            $('#sta_btn_edit').hide().hide()
              .siblings('button').show();
          } else {
            $('#sta_content>form').addClass('disabled');
            $('#sta_btn_save').hide().hide()
              .siblings('button').show();
          }
        } else if (index == 2) {
          if (edit) {
            $('#ap_content>form').removeClass('disabled');
            $('#ap_btn_edit').hide().hide()
              .siblings('button').show();
          } else {
            $('#ap_content>form').addClass('disabled');
            $('#ap_btn_save').hide().hide()
              .siblings('button').show();
          }
        }
      }
      
      function reqTab(index) {
        if (index == 0) {
          $.getJSON('/api/info.lua', function(data){
            if (data) {
              updateInfo(data);
            } else {
              showTip('请求信息失败！', 'danger', 3000);
            }
            switchUIEditInfo(0, false);
          });
        } else if (index == 1) {
          $.getJSON('/api/sta.lua', function(data){
            if (data) {
              updateStation(data);
            } else {
              showTip('请求信息失败！', 'danger', 3000);
            }
            switchUIEditInfo(1, false);
          });
        } else if (index == 2) {
          $.getJSON('/api/ap.lua', function(data){
            if (data) {
              updateAp(data);
            } else {
              showTip('请求信息失败！', 'danger', 3000);
            }
            switchUIEditInfo(2, false);
          });
        } else {
          switchUIEditInfo(index, false);
        }
      }

      function updateInfo(data) {
        function fmtData(data) {
          return data + ' (' + toSize(data) + ')';
        }

        let htmlData = {
          user: data.user,
          chipid: data.cid,
          free: fmtData(data.mfree),
          use: fmtData(data.muse),
          fid: data.fid,
          fsize: fmtData(data.fsize),
          fmode: data.fmode,
          fspeed: toSpeed(data.fspeed),
          amac: data.amac,
          smac: data.smac,
          ver: data.ver,
        };

        let html = $('#template-info').html()
        $('#table_info').html(html.format(htmlData));
      }
      function updateStation(data) {
        $('#sta_input_ssid').val(data.ssid);
        $('#sta_input_pwd').val('');
      }
      function updateAp(data) {
        $('#ap_input_ssid').val(data.ssid);
        $('#ap_input_pwd').val('');
        $('#ap_input_ip').val(data.ip);
        $('#ap_input_netmask').val(data.netmask);
        $('#ap_input_gateway').val(data.gateway);
      }

      $('.tab_nav>ul>li').click(function() {
        tabAClick($(this).index());
      });

      $('#sta_btn_edit').click(function() {
        switchUIEditInfo(1, true);
      });
      $('#sta_btn_save').click(function() {
        $('.box_content>div').eq(0).show()
          .siblings('div').hide();
        // save
        $.ajax({
          type: "PUT",
          dataType: "json",
          url: "/api/sta.lua" ,
          data: $('#sta_content>form').serialize(),
          success: function (result) {
            if (result) {
              showTip('保存成功！', 'success', 3000);
              updateStation(result);
              switchUIEditInfo(1, false);
            } else {
              $('.box_content>div').eq(1+1).show()
                .siblings('div').hide();
              showTip('保存失败！', 'danger', 3000);
            }
          }
        });
      });
      $('#sta_scanap').click(function() {
        $('#sta_scanap').addClass('loading').prop('disabled', true);
        function onDataArrive(data) {
          if (!data) return;
          if (data.status == 1) {
            setTimeout(function() {
              $.getJSON('/api/scanap.lua', onDataArrive);
            }, 1000);
            return;
          }
          let resJson = data.data
          $('#sta_scanap').removeClass('loading').prop('disabled', false);
					let template = $('#template-sta-aplist').html();
					let cos45 = sin45 = 0.70710678118655;
					let html = '';
					for(ssid in resJson) {
						let r = 0.3333 * parseInt(resJson[ssid].rssi) + 33.3333;
						r = r > 20 ? 20 : (r < 0 ? 0 : r)

						html += template.format(
							15 - r * cos45
							, 20 - r * sin45
							, r
							, 15 + r * cos45
							, ssid
						);
					}
					$('#sta_aplist').html(html)
					$('#sta_aplist_modal').addClass('active');

					$("#sta_aplist div").click(function() {
						$('#sta_aplist_modal').removeClass('active');

						var ssid = $(this).children('.chip-content').html()
						$('#sta_input_ssid').val(ssid);						
					});
          $("#sta_aplist_modal .modal-overlay").click(function() {
						$('#sta_aplist_modal').removeClass('active');
          });
        }
        $.getJSON('/api/scanap.lua', {update:true}, onDataArrive);
      });

      $('#ap_btn_edit').click(function() {
        switchUIEditInfo(2, true);
      });
      $('#ap_btn_save').click(function() {
        $('.box_content>div').eq(0).show()
          .siblings('div').hide();
        // save
        $.ajax({
          type: "PUT",
          dataType: "json",
          url: "/api/ap.lua" ,
          data: $('#ap_content>form').serialize(),
          success: function (result) {
            if (result) {
              showTip('保存成功！', 'success', 3000);
              updateAp(result);
              switchUIEditInfo(2, false);
            } else {
              $('.box_content>div').eq(2+1).show()
                .siblings('div').hide();
              showTip('保存失败！', 'danger', 3000);
            }
          }
        });
      });

      tabAClick(0);
    });
  </script>
</head>

<body>

  <div class="tab_nav">
    <ul class="tab tab-block">
      <li class="tab-item"><a>信息</a></li>
      <li class="tab-item"><a>联网</a></li>
      <li class="tab-item"><a>热点</a></li>
      <li class="tab-item"><a>GPIO</a></li>
      <li class="tab-item"><a>MQTT</a></li>
      <li class="tab-item"><a>系统</a></li>
    </ul> 
  </div>
  <div class="title_info bg-grey padding">
    <section class="text-center"><p>终端基本信息</p></section>
    <section class="text-center"><p>配置终端接入一个无线网络</p></section>
    <section class="text-center"><p>配置终端热点信息</p></section>
    <section class="text-center"><p>配置终端GPIO</p></section>
    <section class="text-center"><p>配置终端接入MQTT</p></section>
    <section class="text-center"><p>配置终端系统操作</p></section>
  </div>
  <div class="box_content">
    <div class="loading loading-lg padding"></div>
    <div>
      <table id="table_info" class="table"></table>
    </div>
    <div id="sta_content" class="padding">
      <form class="disabled">
        <div class="form-group">
          <label class="form-label" for="sta_input_ssid">SSID</label>
          <div class="input-group">
            <input type="text" class="form-input" id="sta_input_ssid" name="ssid" placeholder="无线网络名">
            <button type="button" class="btn btn-link input-group-btn" id="sta_scanap">附近网络</button>
          </div>
        </div>
        <div class="form-group">
          <label class="form-label" for="sta_input_pwd">网络密码</label>
          <input class="form-input" type="password" id="sta_input_pwd" name="pwd" placeholder="无线网络密码（无密码请留空）">
        </div>
      </form>
      <div class="padding">
        <button id="sta_btn_edit" type="button" class="btn btn-primary float-right">编辑</button>
        <button id="sta_btn_save" type="button" class="btn btn-primary float-right">保存</button>
      </div>
    </div>
    <div id="ap_content" class="padding">
      <form class="disabled">
        <div class="form-group">
          <label class="form-label" for="ap_input_ssid">SSID</label>
          <input class="form-input" type="text" id="ap_input_ssid" name="ssid" placeholder="无线网络名">
        </div>
        <div class="form-group">
          <label class="form-label" for="ap_input_pwd">网络密码</label>
          <input class="form-input" type="password" id="ap_input_pwd" name="pwd" placeholder="无线网络密码（无密码请留空）">
        </div>
        <div class="form-group">
          <label class="form-label" for="ap_input_ip">IP地址</label>
          <input class="form-input" type="text" id="ap_input_ip" name="ip" placeholder="IP地址">
        </div>
        <div class="form-group">
          <label class="form-label" for="ap_input_netmask">子网掩码</label>
          <input class="form-input" type="text" id="ap_input_netmask" name="netmask" placeholder="子网掩码">
        </div>
        <div class="form-group">
          <label class="form-label" for="ap_input_gateway">默认网关</label>
          <input class="form-input" type="text" id="ap_input_gateway" name="gateway" placeholder="默认网关">
        </div>
      </form>
      <div class="padding">
        <button id="ap_btn_edit" type="button" class="btn btn-primary float-right">编辑</button>
        <button id="ap_btn_save" type="button" class="btn btn-primary float-right">保存</button>
      </div>
    </div>
    <div id="gpio_content" class="padding">GPIO</div>
    <div id="mqtt_content" class="padding">mqtt</div>
    <div id="sys_content" class="padding">
      <div class="btn-group btn-group-block">
        <button type="button" class="btn btn-link" id="sys_to_default">恢复默认配置</button>
        <button type="button" class="btn btn-link" id="sys_to_default">恢复默认配置</button>
        <button type="button" class="btn btn-link" id="sys_to_default">恢复默认配置</button>
      </div> 
    </div>
  </div>

  <div id="sta_aplist_modal" class="modal">
    <div class="modal-overlay"></div>
    <div class="modal-container">
      <div class="modal-header">
        <div class="modal-title">选择一个无线网络</div>
      </div>
      <div id="sta_aplist" class="modal-body"></div>
    </div>
  </div>

  <div id="tip_box_modal" class="modal">
    <div class="modal-container">
      <div class="toast">
        <label></label>
        <button class="btn btn-clear float-right"></button>
      </div>
    </div>
  </div>
</body>

</html>